/* $Id:relations.cc $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "relations"

#include <sstream>
#include <fstream>
#include "../general/util.h"
#include "../general/log.h"
#include "../general/channel.h"
#include "relations.h"
#include "person.h"
#include "../general/general.h"

relations::relations() {
    who=0;
    type=-1;
    amount=0;
}

// Field : who

class person& relations::getWho() const { if (who==0) throw nullpointer(); return *who; }
void relations::setWho(class person &v) { who=&v; }

// Field : type

const string relationsType[]={"family","teacher","student","friend","enemy"};
const int relations::getType() const { return type; }
const string relations::showType() const {
    if (type<0) return "";
    else return relationsType[type];
}
void relations::setType(const int  v) {
    if (v<0 || (unsigned int)v >= sizeof relationsType/sizeof relationsType[0]) type=-1;
    else type=v;
}
void relations::setType(const string v) {
    type=-1;
    loopArray(relationsType, tp, string) {
        if (v==*tp) {type=tp_i; break; }
    }
    if (type==-1) dbg_state("Enumerate relations.type %s has unknown '%s'", getWho().getName().c_str(), v.c_str());
}

// Field : amount

const int relations::getAmount() const { return amount; }
void relations::setAmount(const int v) { amount=v; }

void relations::save(class channel &ch) {
    ch.write("relations", "");
    ch.write("w", getWho().getName());
    ch.write("t", getType());
    ch.write("a", getAmount());
}

void relations::load(class channel &ch) {
    if (ch.key=="w" || ch.key=="who") {
        if (!person_repo.isPerson(ch.value)) {
            dbg_state("link unknown person %s", ch.value.c_str());
            class person rec;
            rec.setName(ch.value);
            person_repo.setPerson(rec);
        }
        setWho(person_repo.getPerson(ch.value));
        ch.next();
    }
    if (ch.key=="t" || ch.key=="type") { setType(ch.value); ch.next(); }
    if (ch.key=="a" || ch.key=="amount") { setAmount(atoi(ch.value.c_str())); ch.next(); }
}

void relations::xml(ofstream &f, int l, int r) {
    f << ncpy(l, "  ") << "<relations type=\"" << showType() <<
    "\" amount=\"" << getAmount() <<
    "\">" << endl;
    if (r<2) try {
        getWho().xml(f,l+1,r+1);
    } catch (nullpointer n) {}
    f << ncpy(l, "  ") << "</relations>" << endl;
}
